import { Directive, ElementRef, Input, OnInit, ComponentRef, ComponentFactoryResolver, ApplicationRef, Injector, EmbeddedViewRef, OnDestroy, HostListener } from '@angular/core';
import { CheesePopupTipComponent } from './popup-tip.component';
import { PopupTipConfig } from './popup-tip.model';

@Directive({
  selector: '[nsPopupTip]',
  exportAs: 'nsPopupTip'
})
export class CheesePopupTipDirective implements OnInit, OnDestroy {
  @Input('nsPopupTip') message: string = '';
  @Input() nsPopupTipType: 'success' | 'error' | 'info' | 'warning' = 'success';
  @Input() nsPopupTipDuration: number = 2000;
  @Input() nsPopupTipClosable: boolean = false;
  @Input() nsPopupTipPosition: 'top' | 'bottom' | 'left' | 'right' = 'top';
  @Input() nsPopupTipTrigger: 'click' | 'hover' | 'manual' = 'click';
  
  private componentRef: ComponentRef<CheesePopupTipComponent> | null = null;
  
  constructor(
    private el: ElementRef,
    private componentFactoryResolver: ComponentFactoryResolver,
    private appRef: ApplicationRef,
    private injector: Injector
  ) {}
  
  ngOnInit(): void {
    // 预创建组件但不显示
    this.createComponent();
  }
  
  ngOnDestroy(): void {
    this.destroyComponent();
  }
  
  @HostListener('click')
  onClick(): void {
    if (this.nsPopupTipTrigger === 'click') {
      this.show();
    }
  }
  
  @HostListener('mouseenter')
  onMouseEnter(): void {
    if (this.nsPopupTipTrigger === 'hover') {
      this.show();
    }
  }
  
  @HostListener('mouseleave')
  onMouseLeave(): void {
    if (this.nsPopupTipTrigger === 'hover') {
      this.hide();
    }
  }
  
  show(): void {
    if (!this.componentRef) {
      this.createComponent();
    }
    
    if (this.componentRef) {
      this.componentRef.instance.show();
    }
  }
  
  hide(): void {
    if (this.componentRef) {
      this.componentRef.instance.hide();
    }
  }
  
  private createComponent(): void {
    // 创建组件
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(CheesePopupTipComponent);
    this.componentRef = componentFactory.create(this.injector);
    
    // 设置配置
    const config: PopupTipConfig = {
      message: this.message,
      type: this.nsPopupTipType,
      duration: this.nsPopupTipDuration,
      closable: this.nsPopupTipClosable,
      position: this.nsPopupTipPosition
    };
    
    this.componentRef.instance.config = config;
    this.componentRef.instance.targetElement = this.el;
    
    // 附加到应用
    this.appRef.attachView(this.componentRef.hostView);
    
    // 获取DOM元素
    const domElem = (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    
    // 添加到body
    document.body.appendChild(domElem);
  }
  
  private destroyComponent(): void {
    if (this.componentRef) {
      this.appRef.detachView(this.componentRef.hostView);
      this.componentRef.destroy();
      this.componentRef = null;
    }
  }
}